package com.haiheng.module_main.mode

import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.RourePage
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.db.BookInfoSub
import com.haiheng.library_base.db.BookWithdrawalRecordTable
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.api
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.module_main.bean.req.Asset
import com.haiheng.module_main.bean.req.AssetOffInfo
import com.haiheng.module_main.bean.req.BookAssetOffLocationReq
import com.haiheng.module_main.bean.req.BookInfoPageRes
import com.haiheng.module_main.bean.req.SourceInfo
import kotlinx.coroutines.launch

/**
 *
 * @Des: 下架
 * @Author: hwz
 * @Date:2023/6/18 0018
 * @Version: 1.0
 */
class BookWithdrawalViewModel(private val bookInfoViewModel: BookInfoViewModel) :BaseViewModel(){
    fun bookWithDrawalByLayer(layNo:String){
        var req =  BookAssetOffLocationReq()
        var sourceInfo = SourceInfo()
        sourceInfo.dataSourceType = "6"
        sourceInfo.orgCode = AppConstant.getLibraryCode()
        var assetOffInfos = arrayListOf<AssetOffInfo>()
        var assetOffInfo = AssetOffInfo()
        assetOffInfo.containerIdType = 4
        assetOffInfo.outLayNo = layNo //层号类型  0内部层号  5rfid智能书架层架   4真实层架号（物理）目前只能支持这个
        assetOffInfos.add(assetOffInfo)
        req.sourceInfo = sourceInfo
        req.assetOffType = 1 // 0下架（书列表）  1下架（按层）   2剔旧（书列表）
        req.assetOffInfos =  assetOffInfos
        api {
            viewModelScope.launch {
                val request = HttpRequest(API.PATH.BOOK_ASSET_OFF_LOCATION)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .setJsonObjec(req)
                var response  = postJson<HttpResponse>(request)
                if (response.isSuccess == true ){
                    LogUtils.e("书籍下架成功")
                    bookInfoViewModel.showMsg.postValue(response.message)
                }else{
                    if (response.message.isNotBlank()){
                        bookInfoViewModel.showMsg.postValue(response.message)
                    }else{
                        bookInfoViewModel.showMsg.postValue(response.errorMsg)
                    }
                    LogUtils.w("书籍下架失败:${response.toJson()}")
                }
            }
        }
    }

    /**
     * 离线模式下架
     *
     */
    fun bookWithDrawalByOffLine(){
        api {
            bookInfoViewModel.bookListData.value?.forEach {
                if (it.isSelect){
                    var b = BookWithdrawalRecordTable()
                    b.barCode = it.barCode
                    b.recordType = RourePage.BOOK_WITHDRAWAL.name
                    b.dataSourceType = "6"
                    b.orgCode = AppConstant.getLibraryCode()
                    b.assetOffType = 0 // 0下架（书列表）  1下架（按层）   2剔旧（书列表）
                    var db = KVDatabase.getDb()
                    var bookInfoBean = db.bookInfoDao().getBookInfoByBarCode(it.barCode.toString());
                    if (bookInfoBean != null){
                        bookInfoBean.bookOnShelfStatus = 3
                        bookInfoBean.fixedContainerSub = BookInfoSub()
                        bookInfoBean.currentContainerSub = BookInfoSub()
                    }
                    db.bookInfoDao().updateBookInfo(bookInfoBean)
                    var result = db.getBookWithdrawalRecordDao().insert(b)
                    if (result > 0){
                        bookInfoViewModel.showMsg.postValue("本地下架成功")
                    }else{
                        bookInfoViewModel.showMsg.postValue("本地下架失败:${result}")
                    }
                }

            }
        }
    }

    /**
     * 下架
     *
     */
    fun bookWithDrawalByList(){
        if (AppConstant.isOpenOfflineMode()){
            bookWithDrawalByOffLine()
            return
        }
        var req =  BookAssetOffLocationReq()
        var sourceInfo = SourceInfo()
        sourceInfo.dataSourceType = "6"
        sourceInfo.orgCode = AppConstant.getLibraryCode()
        var assetOffInfos = arrayListOf<AssetOffInfo>()
        var assetOffInfo = AssetOffInfo()
        var assets = arrayListOf<Asset>()
        val booklist = bookInfoViewModel.bookListData
        booklist.value?.forEachIndexed { index, value ->
            LogUtils.e("索引 ${index} 的值为 ${value}")
            if (value.isSelect){
                var asset = Asset()
                asset.barCode = value.barCode.toString()
                assets.add(asset)
            }
        }
        assetOffInfo.assets = assets
        assetOffInfos.add(assetOffInfo)
        req.sourceInfo = sourceInfo
        req.assetOffType = 0 // 0下架（书列表）  1下架（按层）   2剔旧（书列表）
        req.assetOffInfos =  assetOffInfos
        api {
            viewModelScope.launch {
                val request = HttpRequest(API.PATH.BOOK_ASSET_OFF_LOCATION)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .setJsonObjec(req)
                var response  = postJson<HttpResponse>(request)
                if (response.isSuccess == true ){
                    LogUtils.e("书籍下架成功")
                    bookInfoViewModel.showMsg.postValue(response.message)
                }else{
                    if (response.message.isNotBlank()){
                        bookInfoViewModel.showMsg.postValue(response.message)
                    }else{
                        bookInfoViewModel.showMsg.postValue(response.errorMsg)
                    }
                    LogUtils.w("书籍下架失败:${response.toJson()}")
                }
            }
        }
    }
}